export const CharacterGLMEventStreamHandler = <T>(
  readable: ReadableStream<Uint8Array>,
  handler: (result: T) => void,
) => {
  const stream = readable.getReader();
  const readStream = (
    reader: ReadableStreamDefaultReader<Uint8Array> | undefined,
  ): any => {
    return reader!.read().then(({ done, value }) => {
      if (done) {
        return false;
      }
      const decoded = new TextDecoder().decode(value);
      const decodedArray = decoded.split("data: ");
      decodedArray.forEach(async (d) => {
        const result = d;
        if (d !== "") {
          try {
            const json: T = { data: JSON.parse(result) } as any;
            json && handler(json);
          } catch {}
        }
      });
      return readStream(reader);
    });
  };
  readStream(stream);
};
